package cn.org.timespace.ons.util.pager;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

public class PagerHelper
{
    public static Pager getPagerInstance(HttpServletRequest request, boolean setParameter)
    {
        Pager pager = new Pager();
        pager.setCurrentPageNum(1);
        pager.setBaseUrl(request.getRequestURI());
        
        if(request.getParameter("cpage")!=null)
        {
            try
            {
                pager.setCurrentPageNum(Integer.parseInt(request.getParameter("cpage")));
            }
            catch (Exception e) {
                
            }
            
        }
        
        if(setParameter)
        {
            Enumeration enumeration = request.getParameterNames();
            try{
            	while(enumeration.hasMoreElements())
                {
                    String key=(String)enumeration.nextElement();
                    String[] values = request.getParameterValues(key);
                    if(values.length>1)
                    {
                       StringBuffer str = new StringBuffer(100);
                       for(String s : values)
                       {
                           if(!"".equals(s))
                                  str.append(s + ",");
                       }
                       //System.out.println(str+"---"+str.length());
                       
                       pager.addParam(key, str.substring(0, str.length()-1));
                    }
                    else
                    {
                        if(!"".equals(values[0]))
                            pager.addParam(key, values[0]);
                    }
                    
                    pager.removeParam("cpage");
                }
            }catch(Exception e){
            	//e.printStackTrace();
            }
            						
            
        }

        request.setAttribute("pager", pager);
        return pager;
    }
    
    public static Pager getPagerInstance(HttpServletRequest request)
    {
        return getPagerInstance(request, true);
    }
    
}
